<?php

namespace App\Services\Until;

use App\Services\BaseService;
use EasyWeChat\Kernel\HttpClient\Response;
use EasyWeChat\MiniApp\Application;
use EasyWeChat\MiniApp\Utils;
use Symfony\Contracts\HttpClient\ResponseInterface as ResponseInterfaceAlias;

class WxService extends BaseService
{

    private static $miniPath = [
        'code2Session' => '/sns/jscode2session ', //小程序登录
    ];

    private static $miniApp;

    public function __construct()
    {
        parent::__construct();
    }

    public static function GetMiniApp()
    {
        if (self::$miniApp == null) {
            self::$miniApp = new Application(config('easywechat.mini_app'));
        }
        return self::$miniApp;
    }

    private static function getResponse(Response|ResponseInterfaceAlias $response)
    {
        if ($response->getStatusCode() != 200) {
            return throw new \Exception("请求微信失败,请稍后再试");
        }
        return $response->getContent();
    }

    public static function codeToSession(string $code)
    {
        $miniApp = self::GetMiniApp();
        $result = $miniApp->getClient()->get(self::$miniPath['code2Session'], [
            'query' => [
                'js_code' => $code,
                'grant_type' => 'authorization_code',
            ],
        ]);
        $resp = self::getResponse($result);
        if (empty($resp['openid'])) {
            businessException('登录失败，请稍后再试');
        }
        return $resp['openid'];
    }
}
